<template>
  <!--  资产管理列表-->
  <div>
    <searchData
        :search-data="searchManageArr"
        :refreshCom="true"
        :isExpand="true"
        @search="search"
    />

    <a-card :bordered="false">
      <b-table
          ref="table"
          size="default"
          class='card-table'
          :scroll="{x:'2400px',y: 'calc(50vh)' }"
          :selectConfig="{use: true, type: 'checkbox',rowKey: 'id' }"
          :out-selected-row-keys.sync="outSelectedRowKeys"
          :rowKey="record => record.id"
          :columns="tabColumnsManage"
          :request="loadData"
          :alert="true"
          :bordered="false"
          :pageSizeOptions="['10','20', '40', '60', '80', '100']"
          show-size-changer
          show-quick-jumper
          showPagination="auto"
      >
        <ExportExcel
            slot="suffix"
            ref="exportExcel"
            :export-list="exportList"
            icon="export"
            file-name="资产管理-导出全部.xlsx"
            button-text="导出全部"
            :beforeDownload="beforeDownloadAll"
        />
        <ExportExcel
            slot="suffix"
            :disabled="outSelectedRowKeys.length===0"
            ref="exportExcel"
            :export-list="exportList"
            icon="export"
            file-name="资产管理-导出选中.xlsx"
            button-text="导出选中"
            :beforeDownload="beforeDownloadSelect"
        />

        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="assetNumber" slot-scope="text, record, index">{{ record.ownerProjectNum + '-' + text }}</span>
        <span slot="discardTime" slot-scope="text, record">{{ formatTime(record.discardTime) }}</span>
        <span slot="allotTime" slot-scope="text, record">{{ formatTime(record.allotTime) }}</span>
        <span slot="enterTime" slot-scope="text, record">{{ formatTime(record.enterTime) }}</span>
        <template
            slot="assetStatus"
            slot-scope="key, record"
        >
          {{ mapAssetStatus(key) }}
        </template>
        <template
            slot="assetCatalogue"
            slot-scope="key, record"
        >
          {{ mapAssetCatalogue(key) }}
        </template>
        <template
            slot="buyCatalogue"
            slot-scope="key, record"
        >
          {{ mapBuyCatalogue(key) }}
        </template>

        <!-- 按钮-->
        <a-button
            slot="prefix"
            v-for="record in actions"
            type="primary"
            v-btnPermission="getBtnPermission(record.key)"
            :key="record.key"
            :loading="loadingExportQrcode && record.key===6"
            @click="handleClick(record.key)">{{ record.title }}
        </a-button>

        <a-popconfirm
            slot="prefix"
            v-show="false"
            :title="'确定要去除'+outSelectedRowKeys.length + '条数据(不可恢复)吗?'" @confirm="() => handleRemove()">
          <a-button
              type="primary"
              v-btnPermission="'dc_006_del_01'"
              :disabled="outSelectedRowKeys.length == 0">删除
          </a-button>
        </a-popconfirm>

        <span slot="operation" slot-scope="text, record">
                <a @click="toDetail(record)">查看</a>
                <span>
                  <a-divider type="vertical"/>
                  <a v-btnPermission="'dc_006_edi_01'" @click="editRecord(record)">编辑</a>
                </span>
        </span>
      </b-table>
    </a-card>
    <div id="code" style="display: none"></div>
  </div>
</template>

<script>
import {mapAssetCatalogue, searchManageArr, tabColumnsManage, mapAssetStatus, mapBuyCatalogue,appendTextDescToQrcode,createQrcode,shareUrl} from '../model'
import {getProjectsList} from "@/api/project/projects";
import {deleteAssetManageListBatch} from "@/api/material/assets/assetManage";
import {listDevice} from "@/api/material/assets/assetManage";
import moment from 'moment'
import ExportExcel from "@/components/exportExcel/ExportExcel.vue";
import {searchOption} from "@/views/construction/overdueNodeManagement/components/monthPlan/model";
import Vue from 'vue'

export default {
  name: 'AssetManage',
  components: {ExportExcel},
  data() {
    return {
      outSelectedRowKeys: [],
      exportList: [{columns: [], datas: []}], // 导出配置项
      tabColumnsManage,
      searchManageArr,
      queryParam: {},
      actions: [
        {key: 1, title: '预调拨'},
        {key: 2, title: '调拨确认'},
        {key: 3, title: '设备闲置'},
        {key: 4, title: '报废/丢失'},
        {key: 5, title: '保管移交'},
        {key: 6, title: '导出二维码'}
      ],
      loadingExportQrcode: false,
      //action对数据状态的要求
      statusFilterMap: new Map([[1,[0,1,2]],[2,[2]],[3,[0,2]],[4,[0,1,2]],[5,[0,1,2]]]),
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let query = Object.assign({}, {pageNum: parameter.pageNo, pageSize: parameter.pageSize, param: this.queryParam})
        return listDevice(query).then((res) => {
          return {
            code: 200,
            data: res.data.list,
            currentPage: res.data.pageNum,
            totalSize: res.data.total,
            totalPage: res.data.firstPage
          }
        })
      },
    }
  },
  methods: {
    search(val) {
      this.queryParam = val
      if(this.queryParam.assetStatus && this.queryParam.assetStatus.length > 0){//[1,2,3]=>1,2,3
        this.queryParam.assetStatus = this.queryParam.assetStatus.join(',')
      }
      this.$refs.table.refresh(true)
    },
    formatTime(time) {
      return time ? moment(time).format('YYYY-MM-DD') : '-'
    },
    mapAssetCatalogue,
    mapAssetStatus,
    mapBuyCatalogue,
    getBtnPermission(type){
      if(type===1){
        return 'dc_006_con_01'
      } else if(type===2){
        return 'dc_006_pre_01'
      } else if(type===3){
        return 'dc_006_idl_01'
      } else if(type===4){
        return 'dc_006_dis_01'
      } else if(type===5){
        return 'dc_006_rem_01'
      } else {
        return ''
      }
    },
    handleClick(type) {
      if (this.outSelectedRowKeys.length === 0) {
        this.$message.warn("请选择要操作的资产")
        return
      }

      if (type === 6) { //导出二维码
        this.exportQrcodeZip()
        return
      }
      //校验数据是否满足条件
      let selectData = this.$refs.table.tableData.filter((item) => this.outSelectedRowKeys.includes(item.id))
      let filterData = selectData.filter((item) => !(this.statusFilterMap.get(type) || []).includes(+item.assetStatus))
      if (filterData.length !== 0) {
        let msg = "选择的数据不满足条件，请点击帮助获取操作说明";
        if(type===1){
          msg = "资产状态为【在用、闲置、待定】才能预调拨"
        } else if( type === 2){
          msg = "资产状态为【待定】的资产才可以调拨确认"
        }else if( type === 3){
          msg = "资产状态为【在用、待定】的资产才能闲置"
        }else if( type === 4){
          msg =  "资产状态为【在用、闲置、待定】才能报废/丢失"
        }else if( type === 5){
          msg = "资产状态为【在用、闲置、待定】才能保管移交"
        }
        this.$message.warn(msg)
        return;
      }
      // console.log('selectData= ', selectData)
      if (type === 2) {
        let preAllotProjectIds = new Set(selectData.map((item) => item.preAllotProjectId) || []);
        console.log('projectIds = ', preAllotProjectIds)
        if (preAllotProjectIds.size === 0) {
          this.$message.warn("资产的预调拨项目不能为空")
          return
        }
        if (preAllotProjectIds.size > 1) {
          this.$message.warn("请选择同一个预调拨项目的资产")
          return
        }
      } else  if (type === 5) {
        //只能移交自己保管的资产
        const keepers = selectData.map(item =>item.keeperId) || []
        const ui = Vue.getAcloudProvider().getUserInfo() || {}
        if(Boolean(keepers.length) && ui.employee){
          const toValidateKeeperId = keepers[0]
           if(ui.employee.id !== toValidateKeeperId){
             this.$message.warn("只能移交自己保管的资产")
             return
           }
        }
      }

      this.$router.push({
        name: 'AssetAction',
        query: {
          type: type,
          title: type === 3 ? '拆除设备列表' : type === 4 ? '报废/丢失设备列表' : type === 5 ? '保管移交设备列表' : '利旧资产列表'
        },
        params: {
          list: [...selectData]
        }
      })
    },
    toDetail(item) {
      this.$router.push({
        name: 'AssetManageEdit',
        params: item,
        query: {
          id: item.id,
          isEdit: 0
        }
      })
    },
    editRecord(item) {
      this.$router.push({
        name: 'AssetManageEdit',
        params: item,
        query: {
          id: item.id,
          isEdit: 1
        }
      })
    },
    handleRemove() {
      deleteAssetManageListBatch(this.outSelectedRowKeys).then(res => {
        if (res.code === '0') {
          this.$refs.table.refresh(false)
        } else {
          this.$message.success('删除失败!')
        }
      })
    },
    exportQrcodeZip() {
      let codeEle = document.getElementById("code")
      let url = shareUrl
      let qrcode = createQrcode(url,codeEle)
      //创建压缩对象
      let zip = new JSZip()
      let selectData = this.$refs.table.tableData.filter((item) => this.outSelectedRowKeys.includes(item.id))
      let that = this
      this.loadingExportQrcode = true
      selectData.forEach((item) => {
        //该方法即可替换qrcode中text的内容信息,生成新的二维码，是为了不重复创建div
        qrcode.clear()
        qrcode.makeCode(url + item.id);
        //获取到所有已经生成好的二维码
        let canvases = codeEle.getElementsByTagName('canvas');
        let btmTexts = [`资产编号 ${item.ownerProjectNum}-${item.assetNumber}`,`资产名称 ${item.assetName}`]
        let newCanvas = appendTextDescToQrcode(codeEle,canvases[0],btmTexts)
        //let imgData = canvases[0].toDataURL('image/png').split('base64,')[1];
        let imgData = newCanvas.toDataURL('image/png').split('base64,')[1];
        let imageName = "资产编号(" + item.ownerProjectNum + "-" + item.assetNumber + ") 资产名称(" + item.assetName + ").png"
        zip.file(imageName, imgData, {base64: true}); //第一个参数是图片名字和后缀
      })
      //下载压缩包
      zip.generateAsync({type: "blob"}).then(function (content) {
        that.loadingExportQrcode = false
        saveAs(content, "资产二维码打包下载(共" + selectData.length + "个).zip");
      });

      qrcode = null
      zip = null
    },
    async beforeDownloadAll() {
      let data = await this.$refs.table.getAllData()
      this.beforeDownload(data)
    },
    beforeDownloadSelect() {
      let tableData = this.$refs.table.tableData || []
      let selectData = tableData.filter( item => this.outSelectedRowKeys.includes(item.id))
      this.beforeDownload(selectData)
    },
    beforeDownload(tableData) {
      let columnsExport = this.$clone(this.tabColumnsManage)
      if(tableData.length === 0){
        this.$message.warn("没有可导出的数据")
        return
      }
      this.exportList = [
        {
          columns: columnsExport,
          datas: tableData.map(item=>{
            return  this.mapItem(item)
          })
        }
      ]
    },
    mapItem(item){
      item.assetCatalogue = this.mapAssetCatalogue(item.assetCatalogue)
      item.assetNumber = item.ownerProjectNum +'-'+item.assetNumber
      item.buyCatalogue = this.mapBuyCatalogue(item.buyCatalogue)
      item.assetStatus = this.mapAssetStatus(item.assetStatus)
      item.discardTime = this.formatTime(item.discardTime)
      item.enterTime = this.formatTime(item.enterTime)
      item.allotTime = this.formatTime(item.allotTime)
      return item
    }
  },
  activated() {
    this.$refs.table.refresh(false)
  }
}

</script>


<style scoped lang="less">
/deep/ .ant-card-body table{
  margin-left: 0;
  margin-right: 0;
}

/deep/ .ant-table-row .ant-table-row-cell-break-word{
  overflow:hidden;
  text-overflow:ellipsis;//溢出部分用省略号代替
  -webkit-line-clamp:1; //设置文本显示1行，想要几行把1替换掉就行
  display: table-cell !important; //将对象作为弹性伸缩盒子模型显示;

  white-space:nowrap;
  word-break: break-all;
}

.card-table /deep/ .ant-table-body {
  min-height: 50vh;
}

/deep/ .card-table .ant-table-tbody > tr > td {
   height: 50px;
}
//调整head行属性
/deep/ .card-table .ant-table-thead > tr > th {
  height: 50px;

}
/deep/ .ant-table-fixed-left .ant-table-thead > tr > th:last-child{
  width: 193px;

}
</style>